package com.sinodata.bsm.cicp.finder.hp;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

public class Swap extends HPFinder {
    private static final Logger logger = Logger.getLogger(Swap.class);
    private static final String SHELL = "swapinfo -mt";
    private static final String STRMATCHER = "total\\s+(\\d+)\\s+.+";

    public static void main(String[] args) {

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String[] swapRes = null;
        BufferedReader reader = null;
        String strLine = null;
        Pattern pattern = Pattern.compile(STRMATCHER);
        try {
            reader = CommandReader.getReader(ip, SHELL, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                if (strLine.trim().length() == 0) {
                    continue;
                }
                Matcher matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    swapRes = new String[4];
                    list.add(swapRes);
                    swapRes[0] = "0";
                    swapRes[1] = "swap";
                    swapRes[2] = getHostName(ip) + " swap";
                    swapRes[3] = matcher.group(1); //交换分区大小
                }
            }
            return list;
        } catch (IOException e) {
            logger.error("failed to get HP Swap ", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return null;
    }
}
